package cn.hutool.bing.pic;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;

public class Main {

	private static String url;
	private static String today;

	public static void main(String[] args) {
		HttpUtil.createServer(8087)
				.addAction("bing", (req, res) -> {
					// 检查缓存
					if (null == url || ObjectUtil.notEqual(today, DateUtil.today())) {
						url = getBingPicUrl();
						today = DateUtil.today();
						Console.log("Today Bing URL: {}", url);
					}

					res.addHeader(Header.LOCATION.getValue(), url).send(HttpStatus.HTTP_MOVED_TEMP);
				}).start();
	}

	private static String getBingPicUrl() {
		final String json = HttpUtil.get("https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1");
		final String url = ReUtil.getGroup1("\"url\":\"(.*?)\"", json);
		return "https://www.bing.com" + url;
	}
}
